<template>
	<el-dialog title="新增模型" v-model="openModel" width="1000px" @open="initOpen" append-to-body :before-close="close"
		@close="close">
		<div class="detailItem">
			<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px">
				<el-form-item label="模型名称" prop="modelName">
					<el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="省" prop="province">
					<el-select v-model="queryParams.province" placeholder="请选择省" @change="chooseProvince" clearable>
						<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="市" prop="city">
					<el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable>
						<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label=" ">
					<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
					<el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>

			<!-- <el-row :gutter="10" class="mb8">
				<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
			</el-row> -->

			<el-table :data="casualtiesList">
				<el-table-column label="模型名称" align="center" prop="modelName">
					<template #default="scope">
						<el-link type="primary" :underline="false" @click="edit(scope.row)">
							{{ scope.row.modelName }}
						</el-link>
					</template>
				</el-table-column>
				<el-table-column label="省" align="center" prop="province" />
				<el-table-column label="市" align="center" prop="city" />
				<el-table-column label="是否默认" align="center" prop="isDefault">
					<template #default="scope">
						<span v-if="scope.row.isDefault == '0'">否</span>
						<span v-if="scope.row.isDefault == '1'">是</span>
					</template>
				</el-table-column>
				<el-table-column label="维护人" align="center" prop="createUserName" />
				<el-table-column label="维护人所属单位" align="center" prop="orgName" />
			</el-table>
			<pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
				@pagination="getList" />
		</div>
		<el-dialog :title="title" v-model="open" width="900px" append-to-body>
			<el-form ref="casualtiesRef" :model="form" :rules="rules" label-width="120px">
				<p class="dialogTitle">{{ title }}</p>
				<el-row>
					<el-col :span="12">
						<el-form-item label="模型名称" prop="modelName" v-if="isCopy">
							{{ form.modelName }}
						</el-form-item>
						<el-form-item label="模型名称" prop="modelName" v-else>
							<el-input v-model="form.modelName" placeholder="请输入模型名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否默认" prop="" v-if="isCopy">
							{{ form.isDefault == '0' ? '否' : '是' }}
						</el-form-item>
						<el-form-item label="是否默认" prop="" v-else>
							<el-select v-model="form.isDefault" disabled style="width: 100%;">
								<el-option v-for="item in [
									{ value: '0', label: '否' },
									{ value: '1', label: '是' },
								]" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="地区" prop="" v-if="isCopy || isEditDefault">
							{{ form.province }} - {{ form.city }}
						</el-form-item>
						<el-form-item label="地区" prop="" v-else>
							<el-form-item label="省" prop="provinceId" label-width="50px">
								<el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"
									style="width: 160px;">
									<el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
							<el-col :span="16">
								<el-form-item label="市" prop="" label-width="50px">
									<el-radio-group v-model="radio" @change="chooseRadio">
										<el-radio label="1">全部</el-radio>
										<el-radio label="2">
											<el-select v-model="form.cityId" placeholder="请输入市" multiple collapse-tags :disabled="isCityEdit"
												style="width: 200px;">
												<el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
												</el-option>
											</el-select>
										</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="维护人" prop="">
							{{ form.createUserName }}
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="维护人单位" prop="">
							{{ form.orgName }}
						</el-form-item>
					</el-col>
				</el-row>
				<div>
					<el-row>
						<el-col :span="6" class="tab-title">
							椭圆衰减模型
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="14" :offset="5" v-if="isCopy">
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">长轴： <vue-latex
									:expression="`I_a=${form.longRatio1}+${form.longRatio2}M-${form.longRatio3}${form.longSymbol}(R_a+10)`" />
							</p>
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">短轴： <vue-latex
									:expression="`I_b=${form.shortRatio1}+${form.shortRatio2}M-${form.shortRatio3}${form.shortSymbol}(R_b+${form.shortRatio4})`" />
							</p>
							<vue-latex :expression="`I_a`" />、<vue-latex :expression="`I_b`" />分别为长短轴烈度，M为震级，<vue-latex
								:expression="`R_a`" />、<vue-latex :expression="`R_b`" />分别为烈度为 <vue-latex :expression="`I`" /> 时长、短半轴的长度。
							<!-- <span style="font-size: 16px;font-weight: bold;font-style: italic;">长轴： I<sub>a</sub> = 4.9024 + 1.3485M - 3.9738 lg(R<sub>a</sub> + 13) </span><br/><br/>
							<span style="font-size: 16px;font-weight: bold;font-style: italic;">短轴： I<sub>b</sub> = 4.3517 + 1.2192M - 3.7429 lg(R<sub>b</sub> + 6) </span><br/><br/>
							I<sub>a</sub>、I<sub>b</sub>分别为长短轴烈度，M为震级，R<sub>a</sub>、R<sub>b</sub>分别为烈度为 I 时长、短半轴的长度。<br/> -->
						</el-col>
						<el-col :span="22" :offset="2" v-else>
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">长轴：
								<vue-latex :expression="`I_a=`" />
								<el-form-item prop="longRatio1" label-width="0" style="display: inline-block;">
									<el-input v-model="form.longRatio1" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`+`" />
								<el-form-item prop="longRatio2" label-width="0" style="display: inline-block;">
									<el-input v-model="form.longRatio2" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`M-`" />
								<el-form-item prop="longRatio3" label-width="0" style="display: inline-block;">
									<el-input v-model="form.longRatio3" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<el-select v-model="form.longSymbol" style="width: 60px;">
									<el-option v-for="item in [
										{ value: 'lg', label: 'lg' },
										{ value: 'In', label: 'In' },
									]" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
								<vue-latex :expression="`(R_a+`" />
								<el-form-item prop="longRatio4" label-width="0" style="display: inline-block;">
									<el-input v-model="form.longRatio4" placeholder="自然数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`)`" />
							</p>
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">短轴：
								<vue-latex :expression="`I_b=`" />
								<el-form-item prop="shortRatio1" label-width="0" style="display: inline-block;">
									<el-input v-model="form.shortRatio1" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`+`" />
								<el-form-item prop="shortRatio2" label-width="0" style="display: inline-block;">
									<el-input v-model="form.shortRatio2" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`M-`" />
								<el-form-item prop="shortRatio3" label-width="0" style="display: inline-block;">
									<el-input v-model="form.shortRatio3" placeholder="保留四位小数" style="width: 100px;" />
								</el-form-item>
								<el-select v-model="form.shortSymbol" style="width: 60px;">
									<el-option v-for="item in [
										{ value: 'lg', label: 'lg' },
										{ value: 'In', label: 'In' },
									]" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
								<vue-latex :expression="`(R_b+`" />
								<el-form-item prop="shortRatio4" label-width="0" style="display: inline-block;">
									<el-input v-model="form.shortRatio4" placeholder="自然数" style="width: 100px;" />
								</el-form-item>
								<vue-latex :expression="`)`" />
							</p>
							<vue-latex :expression="`I_a`" />、<vue-latex :expression="`I_b`" />分别为长短轴烈度，M为震级，<vue-latex
								:expression="`R_a`" />、<vue-latex :expression="`R_b`" />分别为烈度为 <vue-latex :expression="`I`" />
							时长、短半轴的长度。<br />
						</el-col>
					</el-row>
				</div>
				<div v-if="type == '1'">
					<el-row style="margin-top: 30px;">
						<el-col :span="6" class="tab-title">
							破裂尺度公式
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12" :offset="6" v-if="isCopy">
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">
								<vue-latex :expression="`M=${form.formulaRatio1}+${form.formulaRatio2}*log(SRL)`" />
								<!-- M = 5.08 + 1.16 * log(SRL)  -->
							</p>
							<p><vue-latex :expression="`SRL`" />为地表破裂带长度</p>
							<p>最终的长轴长度<vue-latex :expression="`=R_a*2+SRL`" /></p>
							<p>长短轴比例：<vue-latex :expression="`${form.scale}`" /></p>
						</el-col>
						<el-col :span="12" :offset="6" v-else>
							<p style="font-size: 16px;font-weight: bold;font-style: italic;">
								<vue-latex :expression="`M=`" />
								<el-form-item prop="formulaRatio1" label-width="0" style="display: inline-block;">
									<el-input v-model="form.formulaRatio1" placeholder="保留二位小数" style="width: 120px;" />
								</el-form-item>
								<vue-latex :expression="`+`" />
								<el-form-item prop="formulaRatio2" label-width="0" style="display: inline-block;">
									<el-input v-model="form.formulaRatio2" placeholder="保留二位小数" style="width: 120px;" />
								</el-form-item>
								<vue-latex :expression="`*log(SRL)`" />
							</p>
							<p><vue-latex :expression="`SRL`" />为地表破裂带长度</p>
							<p>最终的长轴长度<vue-latex :expression="`=R_a*2+SRL`" /></p>
							<p>长短轴比例：
								<el-form-item prop="scale" label-width="0" style="display: inline-block;">
									<el-input v-model="form.scale" placeholder="保留二位小数" style="width: 120px;" />
								</el-form-item>
							</p>
						</el-col>
					</el-row>
				</div>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="copyForm" v-if="isCopy">复 制</el-button>
					<el-button type="primary" @click="saveForm" v-if="!isCopy && Default == '1'">保 存</el-button>
					<el-button type="primary" @click="editForm" v-if="!isCopy && Default == '0'">保 存</el-button>
					<el-button type="primary" @click="delForm" v-if="!isCopy && Default == '0'">删 除</el-button>
					<el-button plain @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</el-dialog>
</template>

<script setup>
import { page, getById, saveArModel, updateById, deleteById } from '@/api/basicDataManage/earthquakeImpactField.js'
import { getProvince, getProvince2, getChildArea } from "@/api/system/division";

const { proxy } = getCurrentInstance();
const casualtiesList = ref([]);
const isCopy = ref(true);
const Default = ref("1");
const radio = ref("1");
const isCityEdit = ref(true);
const isEditDefault = ref(true);
const open = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const type = ref("");
const emits = defineEmits(['update:openModel'])
const props = defineProps({
	openModel: Boolean,
})
// 保留两位小数
const positive2decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([0-9]+[\d]*(.[0-9]{2}))$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
// 保留四位小数
const positive4decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([0-9]+[\d]*(.[0-9]{4}))$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}

// 自然数校验
const positiveInteger = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([1-9][0-9]*|0)$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
const data = reactive({
	form: {},
	queryParams: {
		page: 1,
		rows: 10,
		province: null,
		city: null,

	},
	rules: {
		taskCode: [
			{ required: true, message: "任务编号不能为空", trigger: "blur" }
		],
		modelName: [
			{ required: true, message: "模型名称不能为空", trigger: "blur" }
		],
		province: [
			{ required: true, message: "省不能为空", trigger: "blur" }
		],
		provinceId: [
			{ required: true, message: "省不能为空", trigger: "change" }
		],
		city: [
			{ required: true, message: "市不能为空", trigger: "blur" }
		],
		cityId: [
			{ required: true, message: "市不能为空", trigger: "blur" }
		],
		area: [
			{ required: true, message: "区/县不能为空", trigger: "blur" }
		],
		areaId: [
			{ required: true, message: "区/县 不能为空", trigger: "blur" }
		],
		longRatio1: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		longRatio2: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		longRatio3: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		longRatio4: [
			{ required: true, message: "输入自然数", trigger: "blur", validator: positiveInteger }
		],
		shortRatio1: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		shortRatio2: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		shortRatio3: [
			{ required: true, message: "保留四位小数", trigger: "blur", validator: positive4decimals }
		],
		shortRatio4: [
			{ required: true, message: "输入自然数", trigger: "blur", validator: positiveInteger }
		],
		formulaRatio1: [
			{ required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
		],
		formulaRatio2: [
			{ required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
		],
		scale: [
			{ required: true, message: "保留两位小数", trigger: "blur", validator: positive2decimals }
		],

	}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询人口伤亡计算模型列表 */
function getList() {
	loading.value = true;
	page(queryParams.value).then(response => {
		casualtiesList.value = response.data.rows;;
		total.value = response.data.total;
		loading.value = false;
	});
}

/** 获取省列表 */
function getProvinceData() {
	getProvince2().then(response => {
		provinceData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
		provinceFormData.value = response.data;
	});
}

function chooseRadio(value) {
	if (value == "2") {
		isCityEdit.value = false
	} else {
		isCityEdit.value = true
		form.value.city = "全部"
		form.value.cityId = ""
	}
}

function chooseProvince(value) {
	queryParams.value.city = null;
	queryParams.value.area = null;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value).then(response => {
		cityData.value = response.data;
	});
	//	provinceData.value.map(item => {//遍历数据
	//		if(item.id == value){
	//			if(item.name == "北京市"||item.name == "天津市"||item.name == "上海市"||item.name == "重庆市"){
	//		    cityData.value.push(JSON.parse(JSON.stringify(item)));
	//			}else{
	//				getChildArea(value).then(response => {
	//			    cityData.value = response.data;
	//				});
	//			}
	//			return;
	//		}   
	//})		
}
const initOpen = () => {
	getAllModelFunc()
}
function getAllModelFunc() {
	casualtiesList.value = []
	page(queryParams.value).then(res => {
		if (res.code == 200) {
			casualtiesList.value = res.data.rows
			total.value = res.data.total
		}
	})
}
function chooseFormProvince(value) {
	form.value.city = null;
	form.value.area = null;
	cityFormData.value = [];
	areaFormData.value = [];
	getChildArea(value).then(response => {
		cityFormData.value = response.data;
	});
}

function chooseCity(value) {
	queryParams.value.areaId = null;
	areaData.value = [];
	getChildArea(value).then(response => {
		areaData.value = response.data;
	});
}

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		id: null,
		modelName: null,
		province: null,
		provinceId: null,
		city: null,
		cityId: null,
		area: null,
		areaId: null,

		smrsNumber1: null,
		smrsNumber2: null,
		injuries: null,
		isDefault: null,
		deathNumber: null,

	};
	proxy.resetForm("casualtiesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.page = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	cityData.value = [];
	areaData.value = [];
	proxy.resetForm("queryRef");
	handleQuery();
}

const close = () => {
	emits('update:openModel', false)
	proxy.resetForm('queryRef')
}
/** 查看按钮操作 */
function edit(row) {
	reset();
	type.value = "";
	const id = row.id
	if (row.isDefault == "1") {
		isCopy.value = true;
		Default.value = "1";
		title.value = "系统默认地震烈度衰减模型";
	} else {
		isCopy.value = false;
		Default.value = "0";
		title.value = "地震烈度衰减模型";
	}
	if (row.type == "0") {
		type.value = "0"
	}
	if (row.type == "1") {
		type.value = "1"
	}

	getById({ id: id }).then(response => {

		form.value = response.data;

		open.value = true;
		if (form.value.city == "全部") {
			radio.value = "1"
			isCityEdit.value = true
		} else {
			radio.value = "2"
			isCityEdit.value = false
		}
		if (form.value.isDefault == "0") {
			isEditDefault.value = true
		} else {
			isEditDefault.value = false
		}

	});
}

/*复制*/
function copyForm() {
	// getModelIntensityForCopy(form.value.id).then(response => { 	
	//   form.value = response.data;
	isCopy.value = false;
	form.value.modelName = null;
	form.value.isDefault = "0";
	// });	
	title.value = "复制地震烈度衰减模型";
}

/*新增*/
function saveForm() {
	proxy.$refs["casualtiesRef"].validate(valid => {
		if (valid) {
			if (radio.value == "1") {
				form.value.cityId = "全部"
			} else {
				if (form.value.cityId != null) {
					form.value.cityId = JSON.parse(JSON.stringify(form.value.cityId)).join(",")
				}

			}
			saveArModel({
				"modelName": form.value.modelName,
				"longRatio1": form.value.longRatio1,
				"longRatio2": form.value.longRatio2,
				"longRatio3": form.value.longRatio3,
				"longRatio4": form.value.longRatio4,
				"longSymbol": form.value.longSymbol,
				"shortRatio1": form.value.shortRatio1,
				"shortRatio2": form.value.shortRatio2,
				"shortRatio3": form.value.shortRatio3,
				"shortRatio4": form.value.shortRatio4,
				"shortSymbol": form.value.shortSymbol,
				"formulaRatio1": form.value.formulaRatio1,
				"formulaRatio2": form.value.formulaRatio2,
				"scale": form.value.scale,
				"isDefault": form.value.isDefault,
				"province": form.value.provinceId,
				"city": form.value.cityId,
				"type": form.value.type,
			}).then(response => {
				proxy.$modal.msgSuccess("新增成功");
				open.value = false;
				getList();
			});
		}
	});


}
/*编辑*/
function editForm() {
	proxy.$refs["casualtiesRef"].validate(valid => {
		if (valid) {
			updateById(form.value).then(response => {
				if (response.message == "修改失败，只能修改自己创建的模型") {

					proxy.$modal.msgWarning(response.message);
				} else {
					proxy.$modal.msgSuccess(response.message);
					open.value = false;
					getList();
				}
				//proxy.$modal.msgSuccess("修改成功");
			});
		}
	});
}
/*删除*/
function delForm() {
	const id = form.value.id;
	proxy.$modal.confirm('是否确认删除？').then(() => {
		deleteById({ id: id }).then(response => {
			if (response.message == "删除失败，只能删除自己创建的模型") {
				proxy.$modal.msgWarning(response.message);
			} else {
				proxy.$modal.msgSuccess(response.message);
				open.value = false;
				getList();
			}
		});
	}).catch(() => { });
}

getList();
getProvinceData();
getProvinceFormData();
</script>
<style scoped lang="scss">
.detailItem {
	padding: 20px 0;
}

.tab-title {
	font-size: 16px;
	font-weight: bold;
	border-left: 4px solid var(--el-color-primary);
	;
	font-family: PingFangSC-Medium;
	padding-left: 10px;
	margin-bottom: 20px;
}

.pagination-container {
	padding: 0px 20px !important;
}
</style>
